﻿@inject ClipboardCopyService ClipboardCopyService
@inject JsInteropService JsInteropService
@inject IStringLocalizerFactory LocalizerFactory
@inject DbService DbService
@implements IDisposable
@using Microsoft.Extensions.Localization

@if (Label != null)
{
    <label for="@Id" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">@Label</label>
}

<div class="relative flex-grow">
    <input type="text" autocomplete="off" id="@Id" class="outline-0 shadow-sm bg-gray-50 border @(Copied ? "border-green-500 border-2" : "border-gray-300") text-gray-900 sm:text-sm rounded-lg block w-full p-2.5 pr-10 dark:bg-gray-700 dark:border-@(Copied ? "green-500" : "gray-600") dark:placeholder-gray-400 dark:text-white" value="@Value" @onclick="CopyToClipboard" readonly>
    @if (Copied)
    {
        <span class="absolute inset-y-0 right-0 flex items-center pr-3 text-green-500 dark:text-green-400">
            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
                <path d="M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z"></path>
                <path d="M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z"></path>
            </svg>
        </span>
    }
</div>

@code {
    /// <summary>
    /// Id for the input field. Defaults to a random GUID if not provided.
    /// </summary>
    [Parameter]
    public string Id { get; set; } = Guid.NewGuid().ToString();

    /// <summary>
    /// The label for the input.
    /// </summary>
    [Parameter]
    public string? Label { get; set; }

    /// <summary>
    /// The value to copy to the clipboard.
    /// </summary>
    [Parameter]
    public string Value { get; set; } = string.Empty;

    private bool Copied => ClipboardCopyService.GetCopiedId() == Id;

    /// <inheritdoc />
    protected override void OnInitialized()
    {
        ClipboardCopyService.OnCopy += HandleCopy;
    }

    private async Task CopyToClipboard()
    {
        // Get the global clipboard clear setting
        var clearAfterSeconds = DbService.Settings.ClipboardClearSeconds;

        var success = await JsInteropService.CopyToClipboardWithClear(Value, clearAfterSeconds);
        if (success)
        {
            ClipboardCopyService.SetCopied(Id);
        }
    }

    private void HandleCopy(string copiedElementId)
    {
        StateHasChanged();
    }

    /// <inheritdoc />
    public void Dispose()
    {
        ClipboardCopyService.OnCopy -= HandleCopy;
    }
}
